#!python
# 
# Base scons build file for pyopensg.
#
import SConsAddons.Options as sca_opts
import SConsAddons.Options.Pyste
import SConsAddons.Options.Boost
import SConsAddons.Options.OpenSG
import SConsAddons.Util as sca_util      # Get the utils
import SConsAddons.Variants as sca_variants
from SConsAddons.EnvironmentBuilder import EnvironmentBuilder
import sys, os, re, string, copy
pj = os.path.join
GetPlatform = SConsAddons.Util.GetPlatform
Export('GetPlatform')
try:
   import wing.wingdbstub       # stuff for debugging
except:
   print '[WRN] Unable to load wing debugging extensions'

# Setup base scons options and settings
EnsureSConsVersion(0,96)
SourceSignatures('MD5')
#SourceSignatures('timestamp')
#TargetSignatures('content')
SetOption('max_drift',30)                  # 30 second drift on MD5 Files
SetOption('implicit_cache',1)
SConsignFile('.sconsign.'+GetPlatform())   # Store all .sconsign stuff in single file

# ###############################
# Setup the build tree
# ###############################
platform = SConsAddons.Util.GetPlatform()
unspecified_prefix = "use-instlinks"
buildDir = "build." + platform      
option_filename = "config.cache." + platform

if GetPlatform() == "win32":
   common_env = Environment()
else:
   common_env = Environment(ENV = os.environ)
common_env["CONFIGUREDIR"] = '.sconf_temp_'+platform
common_env["CONFIGURELOG"] = 'sconf.log_'+platform

# Create variant helper and builder
variant_helper = sca_variants.VariantsHelper()
base_bldr = EnvironmentBuilder()

# Disable debug on windows since we only want things with release run-time
if GetPlatform() == "win32":
   variant_helper.variants["type"][0].remove("debug")
   common_env.Append(CCFLAGS=["/Zm1200"])
   
# ---------- Options ------------ #
opts = sca_opts.Options(files = [option_filename, 'options.custom'], 
                                   args= ARGUMENTS);
pyste_options = sca_opts.Pyste.Pyste("pyste","0.9.26", required=False)
boost_options = sca_opts.Boost.Boost("boost","1.31.1",
                                     useMt = True,
				     useVersion=(GetPlatform()=="win32"),
				     preferDynamic=True,
				     autoLink=True,
                                     libs = ['python',],
                                     required=True)
opensg_options = sca_opts.OpenSG.OpenSG("opensg","1.6.0", required=True)

opts.Add('prefix', 'Installation prefix', unspecified_prefix)
opts.AddOption(sca_opts.SeparatorOption("\nPackage Options"))
opts.AddOption( opensg_options )
opts.AddOption( boost_options )
opts.AddOption( pyste_options )
base_bldr.addOptions(opts)
variant_helper.addOptions(opts)
opts.Process(common_env)

Export('opts', 'opensg_options', 'boost_options', 'pyste_options')

help_text =  """----- PyOpenSG Build system ---
%s
Targets:
   install - Install PyOpenSG.
   type 'scons' to just build the project
"""%opts.GenerateHelpText(common_env)

# Debug option settings
if 0:
   print "---- boost settings ---"
   boost_options.dumpSettings()
   print "---- OpenSG settings ---"
   opensg_options.dumpSettings()

# ----- Package setup ------------ #
# Only do this if we aren't just outputing help text
if not SConsAddons.Util.hasHelpFlag():
   try:
      opts.Save(option_filename, common_env)
   except LookupError, le:
      pass
   
   # -- Common builder settings
   variant_helper.readOptions(common_env)
   base_bldr.readOptions(common_env)
   base_bldr.enableWarnings()   
  
 # Apply any common package options
   # Update environment for boost options
   if boost_options.isAvailable():
      boost_options.apply(common_env)    
     
   # If defaulting to instlinks prefix:
   #  - Use symlinks
   #  - Manually set the used prefix to the instlinks of the build dir
   if common_env['prefix'] == unspecified_prefix:
      if hasattr(os,'symlink'):
         common_env['INSTALL'] = sca_util.symlinkInstallFunc
      common_env['prefix'] = pj( Dir('.').get_abspath(), buildDir, 'instlinks')

   # --- Setup Installation Paths --- #
   # Setup a map with the paths that we will install everything to
   # - Note: this is used throughout the build to keep things consistent
   base_paths = {}
   base_paths['base']       = common_env['prefix']
   base_paths['lib']        = pj(base_paths['base'],'lib')
   base_paths['python_lib'] = pj(base_paths['base'],'lib','python')
   base_paths['include']    = pj(base_paths['base'],'include')
   base_paths['share']      = pj(base_paths['base'],'share','IOV')
   base_paths['app_base']   = pj(base_paths['share'],'apps')
   base_paths['test_base']  = pj(base_paths['share'],'test')   
   
   print "Using prefix: ", base_paths["base"]
   print "types: ",    variant_helper.variants["type"] 
   print "libtypes: ", variant_helper.variants["libtype"] 
   print "archs: ",    variant_helper.variants["arch"] 
   
   # ----- Python binding code generation ------ #
   # - Put here because we want to run code generation in the source tree
   #      but build it in the build tree. (could probaly be done better)
   # - Generate one source list for each module.
   opensg_pymod_srcs = []
   Export('opensg_pymod_srcs','common_env')
   SConscript(pj('src','pyste','SConscript'))
   
   # --- FOR EACH VARIANT --- #
   for combo in variant_helper.iterate(locals(), base_bldr, common_env):
      print "   Processing combo: ", ", ".join(['%s:%s'%(i[0],i[1]) for i in combo.iteritems()])
      
      inst_paths = copy.copy(base_paths)
      # If x64 then put in a different directory
      if "x64" == combo["arch"]:
         inst_paths['python_lib'] = inst_paths['python_lib'] + '64'      
      # If debug version, put in a debug subdir
      if "optimized" != combo["type"]:
         inst_paths["python_lib"] = pj(inst_paths["python_lib"],combo["type"])     
      
      Export('build_env','inst_paths','opts','variant_pass','combo')      

      full_build_dir = pj(buildDir,combo_dir)         
      SConscript(dirs=['src'], build_dir=full_build_dir, duplicate=0)
   
   # close off build
   common_env.Alias('install', base_paths['base'])
  
# --------- Finish up ------------ #
Default(".");

Help(help_text);

# end
